﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;
using System.Collections.Generic;

namespace msBsc.AppLogic.DataAlc
{
    /// <summary>
    /// 订单 下单 状态
    /// </summary>
    public class CBizOrdersInfo : CustBizObject
    {
        private CDmDjkOrdersInfo m_CDmDjkOrdersInfo = new CDmDjkOrdersInfo();
        private CDmDjkOrdersInfo oDmDjkOrdersInfo
        {
            get { return m_CDmDjkOrdersInfo; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizOrdersInfo()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmDjkOrdersInfo.DJK_ORDERS_INFO);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["ORDERS_INFO_ID"];
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }


            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }

        protected override bool BeforeRowDeletedR(DataRow drw)
        {
            //using (msBsc.AppLogic.DataAlc.CBizShpPageColumn objtem = new CBizShpPageColumn())
            //{
            //    DataSet ds = objtem.SelectByPageNo(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //} 
            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {

            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowDeletedR(DataRow drw)
        {
            return true;
        }


        /// <summary>
        /// 添加订单信息
        /// </summary>
        /// <param name="vehiclesInfo">车辆信息(格式要求：车辆编号之间以'|'间隔，例如：Vehicle1ID|Vehicle2ID|Vehicle3ID.....)</param>
        /// <param name="startTime">开始服务时间</param>
        /// <param name="stopTime">结束服务时间</param>
        /// <param name="orderExpanation">备注内容</param>
        /// <returns></returns>
        public string AddOrderInfo(string vehiclesInfo, string startTime, string stopTime, string orderExpanation)
        {
            if (!msBsc.SvRef.UserInfo.Online || string.IsNullOrEmpty(msBsc.SvRef.UserInfo.Operator))
            {
                return "NOTONLINE";
            }

            #region 基本信息验证
            if (string.IsNullOrEmpty(vehiclesInfo))
            {
                return "请选择至少一辆车进行预订";
            }
            if (string.IsNullOrEmpty(startTime)
                || string.IsNullOrEmpty(stopTime))
            {
                return "服务开始日期和结束日期不能为空";
            }

            DateTime startDate, stopDate;

            if (!DateTime.TryParse(startTime, out startDate)
                || !DateTime.TryParse(stopTime, out stopDate))
            {
                return "服务开始日期或结束日期有误，请调整";
            }

            if (startDate < this.dtCurrDateTime)
            {
                return "服务开始日期必须大于当前日期";
            }
            if (stopDate < startDate)
            {
                return "服务结束日期必须大于开始日期";
            }
            #endregion

            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                #region 添加订单信息
                stopDate = (stopDate.Hour == 0 && stopDate.Minute == 0 && stopDate.Second == 0) ? stopDate : stopDate.AddDays(1);

                TimeSpan tsp = stopDate.Date.Subtract(startDate.Date);
                int serviceDays = tsp.Days;

                string orderId = this.DataObj.NewID();

                string solderid;

                DataSet productDs = new msBsc.AppLogic.DataAlc.CBizDJkOrdersDetail().AddOrderDetail(orderId, vehiclesInfo, serviceDays, 1, out solderid);

                if (productDs == null
                    || productDs.Tables[0].Rows.Count <= 0)
                {
                    return "订购车辆信息失败，请至少选择一辆车进行预订！";
                }


                decimal totalPrice = 0;
                decimal discountAMT = 0;
                for (int i = productDs.Tables[0].Rows.Count - 1; i >= 0; i--)
                {
                    totalPrice += Convert.ToDecimal(productDs.Tables[0].Rows[i]["PRODUCT_STRIKE_PRICE"]) * Convert.ToInt32(productDs.Tables[0].Rows[i]["PRODUCT_QTY"]);
                    discountAMT += Convert.ToDecimal(productDs.Tables[0].Rows[i]["DISCOUNT_AMT"]) * Convert.ToInt32(productDs.Tables[0].Rows[i]["PRODUCT_QTY"]);
                }

                DataSet ds = new CDmDjkOrdersInfo();
                DataRow dr = ds.Tables[0].NewRow();

                dr["ORDERS_INFO_ID"] = orderId;
                dr["ORDER_TIME"] = this.dtCurrDateTime;
                dr["ORDER_CODE"] = "dlz" + this.dtCurrDateTime.ToString("yyyyMMddHHmmss") + msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("ORDER_CODE", "", 4);
                dr["ORDER_CONTENT"] = orderExpanation;
                dr["ORDER_STATUS"] = 1;
                dr["ORDER_BY_IP"] = msBsc.Cls.CommValiCollection.GetIp();
                dr["ORDER_START_TIME"] = startDate;
                dr["ORDER_STOP_TIME"] = stopDate;
                dr["ORDER_DJACK_CHECK"] = 0;
                dr["ORDER_TOTAL_BALANCE"] = totalPrice;
                dr["DISCOUNT_AMT"] = discountAMT;
                dr["PAYABLE_AMT"] = totalPrice - discountAMT;
                dr["ORDER_IS_CUSTOMER_DEL"] = 0;
                dr["ORDER_IS_DJACK_DEL"] = 0;
                dr["ORDER_HAS_REFUND"] = 0;
                dr["ORDER_BUYER_ID"] = msBsc.SvRef.UserInfo.Operator;
                dr["ORDER_SOLDER_ID"] = solderid;
                dr["ORDER_REFUND_FINISH"] = 0;

                ds.Tables[0].Rows.Add(dr);
                this.Update(ds);
                #endregion

                ts.Complete();
                return "OK";
            }
        }

        /// <summary>
        /// 地接客确认订单信息
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public string CheckOrderInfo(string orderId)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return "订单编号不能为空";
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("orderId", ParameterDirection.Input, EDbType.String, 36, orderId.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("djackId", ParameterDirection.Input, EDbType.String, 36, msBsc.SvRef.UserInfo.Operator));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT A.* FROM DJK_ORDERS_INFO A WHERE A.ORDERS_INFO_ID=@orderId AND A.ORDERS_SOLDER_ID=@djackId", parmCollection);

            if (ds.Tables[0].Rows.Count != 1)
            {
                return "订单编号有误";
            }

            ds.Tables[0].TableName = this.DataObj.TableName;

            ds.Tables[0].Rows[0]["ORDER_STATUS"] = (int)OrderStatusEnum.SolderChecked;
            ds.Tables[0].Rows[0]["ORDER_DJACK_CHECK"] = 1;
            ds.Tables[0].Rows[0]["DJACK_CHECK_TIME"] = this.dtCurrDateTime;

            this.Update(ds);
            return "OK";
        }

        public DataSet GetOrderInfoById(string orderId)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("orderId", ParameterDirection.Input, EDbType.String, 36, orderId));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_INFO WHERE ORDERS_INFO_ID=@orderId", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="orderStatus">修改后状态</param>
        /// <returns>修改结果</returns>
        public bool ModifyOrderStatus(string orderId, OrderStatusEnum orderStatus)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return false;
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("orderId", ParameterDirection.Input, EDbType.String, 36, orderId));
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_INFO WHERE ORDERS_INFO_ID=@orderId", parmCollection);

            if (ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            ds.Tables[0].TableName = this.DataObj.TableName;

            ds.Tables[0].Rows[0]["ORDERS_STATUS"] = (int)orderStatus;
            this.Update(ds);
            return true;
        }

        /// <summary>
        /// 查询用户订单信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isBuyer"></param>
        /// <param name="selectStatus"></param>
        /// <returns></returns>
        public DataSet GetPagedOrdersInfo(int pageIndex, int pageSize, bool isBuyer, OrderStatusEnum selectStatus)
        {
            pageIndex = pageIndex <= 0 ? 1 : pageIndex;
            pageSize = pageSize <= 0 ? 10 : pageSize;

            string buyerId = isBuyer ? msBsc.SvRef.UserInfo.Operator : "";
            string solderId = isBuyer ? "" : msBsc.SvRef.UserInfo.Operator;

            if (string.IsNullOrEmpty(buyerId)
                && string.IsNullOrEmpty(solderId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("pageindex", ParameterDirection.Input, EDbType.Integer, 10, pageIndex));
            parmCollection.Add(new CDbParm("pagesize", ParameterDirection.Input, EDbType.Integer, 10, pageSize));
            parmCollection.Add(new CDbParm("buyerid", ParameterDirection.Input, EDbType.String, 36, buyerId));
            parmCollection.Add(new CDbParm("solderid", ParameterDirection.Input, EDbType.String, 36, solderId));
            parmCollection.Add(new CDbParm("orderstatus", ParameterDirection.Input, EDbType.Integer, 10, (int)selectStatus));

            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_ORDERS_INFO_FOR_VIEW", parmCollection);

            return ds;
        }


        /// <summary>
        /// 订单状态处理
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="orderStatus">订单状态</param>
        /// <returns>修改结果</returns>
        public string OrderStatus(string orderId, OrderStatusEnum orderStatus)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return "信息不能为空";
            }
            //根据用户ID得到用户类型 用户账号类型:1普通客户，2地接客
            string userId = msBsc.SvRef.UserInfo.Operator;
            DataSet dsReg = GetAccountTypeById(userId);
            if (dsReg == null || dsReg.Tables[0].Rows.Count <= 0)
            {
                return "该用户不存在";
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderId", ParameterDirection.Input, EDbType.String, 36, orderId.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("UserId", ParameterDirection.Input, EDbType.String, 36, userId.Replace("'", "").Replace(",", "','")));

            int acctionType = Convert.ToInt32(dsReg.Tables[0].Rows[0]["CUSTOMER_ACCOUNT_TYPE"]);

            #region 地接客订单状态处理
            if (acctionType == 2)
            {
                //判断是否可以交易
                string[] solsers = WhetherBond(userId);
                if (Convert.ToBoolean(solsers[0]))
                {
                    return solsers[1];
                }


                DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_SOLDER_ID,ORDER_STATUS
    FROM DJK_ORDERS_INFO
    WHERE ORDER_IS_DJACK_DEL=0 AND ORDERS_INFO_ID=@OrderId AND ORDER_SOLDER_ID=@UserId", parmCollection);
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    return "该地接客不存在此订单";
                }
                ds.Tables[0].TableName = this.TableName;
                DataRow dr = ds.Tables[0].Rows[0];

                if (Convert.ToInt32(orderStatus) == 2)//商家确认
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.WaitingCheck)
                    {
                        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                    }
                    else
                    {
                        return "当前订单状态不是等待确认";
                    }
                }
                else if ((OrderStatusEnum)Convert.ToInt32(orderStatus) == OrderStatusEnum.SurePayBack)//确认退款
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.ApplyPayBack)
                    {
                        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                    }
                    else
                    {
                        return "当前订单不是申请退款，不能确认退款";
                    }
                }
                else if ((OrderStatusEnum)Convert.ToInt32(orderStatus) == OrderStatusEnum.Refusal)//拒绝退款
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.ApplyPayBack)
                    {
                        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                    }
                    else
                    {
                        return "当前订单不是申请退款，不能拒绝退款";
                    }
                }
                this.Update(ds);
            }
            #endregion

            #region 游客订单状态处理
            if (acctionType == 1)
            {
                DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_BUYER_ID,ORDER_STATUS
    FROM DJK_ORDERS_INFO
    WHERE ORDER_IS_CUSTOMER_DEL=0 AND ORDERS_INFO_ID=@OrderId AND ORDER_BUYER_ID=@UserId", parmCollection);
                ds.Tables[0].TableName = this.TableName;
                DataRow dr = ds.Tables[0].Rows[0];
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    return "该游客不存在此订单";
                }
                if ((OrderStatusEnum)Convert.ToInt32(orderStatus) == OrderStatusEnum.Finished)//完成服务
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.PaiedAll)
                    {
                        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                    }
                    else
                    {
                        return "当前订单状态未支付，不能完成服务";
                    }
                }
                else if ((OrderStatusEnum)Convert.ToInt32(orderStatus) == OrderStatusEnum.ApplyPayBack)//申请退款
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDERS_STATUS"].ToString()) == OrderStatusEnum.PaiedAll)
                    {
                        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                    }
                    else
                    {
                        return "当前订单状态未支付，不能申请退款";
                    }
                }
                //else if ((OrderStatusEnum)Convert.ToInt32(orderStatus) == OrderStatusEnum.CancelOrder)//取消订单
                //{
                //    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.WaitingCheck)
                //    {
                //        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                //    }
                //    else
                //    {
                //        return "当前订单状态是等待确认，不能取消";
                //    }
                //}
                else if ((OrderStatusEnum)Convert.ToInt32(orderStatus) == OrderStatusEnum.RefundCanceled)//取消退款
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.ApplyPayBack)
                    {
                        dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                    }
                    else
                    {
                        return "当前订单状态不是申请退款中，不能取消退款";
                    }
                }
                this.Update(ds);
            }
            #endregion


            //地接客
            return "OK";
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="orderStatu">订单状态</param>
        /// <returns></returns>
        public string DeleteOrderStatus(string orderId, OrderStatusEnum orderStatu)
        {
            #region 基本信息判断
            if (string.IsNullOrEmpty(orderId))
            {
                return "订单编号不能为空";
            }
            string userId = msBsc.SvRef.UserInfo.Operator;
            if (string.IsNullOrEmpty(userId))
            {
                return "用户ID不能为空";
            }
            //根据用户ID判断用户类型
            DataSet dsReg = GetAccountTypeById(userId);
            if (dsReg.Tables[0].Rows.Count <= 0)
            {
                return "该用户不存在";
            }
            #endregion

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderId", ParameterDirection.Input, EDbType.String, 36, orderId.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("UserId", ParameterDirection.Input, EDbType.String, 36, userId.Replace("'", "").Replace(",", "','")));

            #region 地接客删除订单
            if (Convert.ToInt32(dsReg.Tables[0].Rows[0]["CUSTOMER_ACCOUNT_TYPE"]) == 2)
            {
                DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_SOLDER_ID,ORDER_STATUS,ORDER_IS_DJACK_DEL,
    ORDER_DJACKDEL_TIME FROM DJK_ORDERS_INFO
    WHERE ORDER_IS_DJACK_DEL=0 AND ORDERS_INFO_ID=@OrderId AND ORDER_SOLDER_ID=@UserId", parmCollection);
                DataRow dr = ds.Tables[0].Rows[0];
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    return "该地接客不存在此订单";
                }
                if ((OrderStatusEnum)Convert.ToInt32(orderStatu) == OrderStatusEnum.DeleteOrder)
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.Finished ||
                    (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.CancelOrder ||
                    (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.CloseStream)
                    {
                        dr["ORDER_IS_DJACK_DEL"] = 1;
                        dr["ORDER_DJACKDEL_TIME"] = this.dtCurrDateTime;
                        dr["ORDER_STATUS"] = OrderStatusEnum.DeleteOrder;
                    }
                    else
                    {
                        return "订单当前状态不允许删除";
                    }
                }
                ds.Tables[0].TableName = this.TableName;
                this.Update(ds);

            }
            #endregion

            #region 游客删除订单
            if (Convert.ToInt32(dsReg.Tables[0].Rows[0]["CUSTOMER_ACCOUNT_TYPE"]) == 1)
            {
                DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_BUYER_ID,ORDER_STATUS,
    ORDER_IS_CUSTOMER_DEL,ORDER_CUSDEL_TIME FROM DJK_ORDERS_INFO
    WHERE ORDER_IS_CUSTOMER_DEL=0 AND ORDERS_INFO_ID=@OrderId AND ORDER_BUYER_ID=@UserId", parmCollection);
                DataRow dr = ds.Tables[0].Rows[0];
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    return "该游客不存在此订单";
                }
                if ((OrderStatusEnum)Convert.ToInt32(orderStatu) == OrderStatusEnum.DeleteOrder)
                {
                    if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.Finished ||
                    (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.CancelOrder ||
                    (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.CloseStream)
                    {
                        dr["ORDER_IS_CUSTOMER_DEL"] = 1;
                        dr["ORDER_CUSDEL_TIME"] = this.dtCurrDateTime;
                        dr["ORDER_STATUS"] = OrderStatusEnum.DeleteOrder;
                    }
                    else if ((OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.WaitingCheck ||
                           (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString()) == OrderStatusEnum.SolderChecked)
                    {
                        dr["ORDER_IS_CUSTOMER_DEL"] = 1;
                        dr["ORDER_CUSDEL_TIME"] = this.dtCurrDateTime;
                        dr["ORDER_STATUS"] = OrderStatusEnum.CancelOrder;
                    }
                    else
                    {
                        return "订单当前状态不允许删除";
                    }
                    ds.Tables[0].TableName = this.TableName;
                    this.Update(ds);
                }
            }
            #endregion

            return "OK";
        }

        /// <summary>
        /// 根据用户ID得到用户账号类型
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>CUSTOMER_ACCOUNT_TYPE：账号类型</returns>
        public DataSet GetAccountTypeById(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("USERID", ParameterDirection.Input, EDbType.String, 36, userId.Replace("'", "").Replace(",", "','")));
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT A.CUSTOMER_ACCOUNT_TYPE
    FROM DJK_CUSTOMER_REGISTER A
    WHERE A.CUSTOMER_REGISTER_ID=@USERID", parmCollection);
            CBizCustomerRegister register = new CBizCustomerRegister();
            ds.Tables[0].TableName = register.TableName;
            return ds;
        }

        /// <summary>
        /// 获取订单交易状态
        /// </summary>
        /// <param name="ordersInfoId">订单ID</param>
        /// <param name="ordersBuyerId">用户ID</param>
        public OrderStatusEnum GetOrderStatus(string ordersId, string userId)
        {
            if (string.IsNullOrEmpty(ordersId) || string.IsNullOrEmpty(userId))
            {
                return OrderStatusEnum.CloseStream;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderId", ParameterDirection.Input, EDbType.String, 36, ordersId));
            parmCollection.Add(new CDbParm("UserId", ParameterDirection.Input, EDbType.String, 36, userId));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_BUYER_ID,ORDER_STATUS
    FROM DJK_ORDERS_INFO
    WHERE ORDERS_INFO_ID=@OrderId AND ORDER_BUYER_ID=@UserId", parmCollection);

            return ds.Tables[0].Rows.Count > 0 ? ((OrderStatusEnum)ds.Tables[0].Rows[0]["ORDER_STATUS"]) : OrderStatusEnum.CloseStream;
        }

        /// <summary>
        /// 根据订单ID  车辆ID 获取订单详细信息
        /// </summary>
        /// <returns></returns>
        public DataTable GetOrdersInfoByID(string ordersInfoID, string product)
        {
            if (string.IsNullOrEmpty(ordersInfoID))
            {
                return null;
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderInfoID", ParameterDirection.Input, EDbType.String, 36, ordersInfoID));
            parmCollection.Add(new CDbParm("PRODUCT", ParameterDirection.Input, EDbType.String, 36, product));
            DataSet ds = this.DataObj.QueryBySQL(@" SELECT OI.*,CR.CUSTOMER_DEFAULT_PIC,CR.CUSTOMER_NICK,OD.PRODUCT_ID,OD.PRODUCT_NME,OD.IMG_URL,OD.PRODUCT_STRIKE_PRICE,
OD.DISCOUNT_AMT FROM 
 (SELECT ORDERS_INFO_ID,ORDER_CODE,ORDER_TIME,ORDER_CONTENT,ORDER_STATUS,PAYABLE_AMT,ORDER_START_TIME,ORDER_STOP_TIME,
PAID_AMT,ORDER_BUYER_ID,ORDER_SOLDER_ID
FROM [dbo].[DJK_ORDERS_INFO](NOLOCK)
WHERE ORDERS_INFO_ID=@OrderInfoID) OI
LEFT JOIN DJK_CUSTOMER_REGISTER(NOLOCK) CR ON OI.ORDER_SOLDER_ID=CR.CUSTOMER_REGISTER_ID
LEFT JOIN DJK_ORDERS_DETAIL(NOLOCK) OD ON OD.ORDERS_INFO_ID=OI.ORDERS_INFO_ID AND OD.PRODUCT_ID=@PRODUCT", parmCollection);

            return ds.Tables[0];
        }

        public string CheckOrderPaied(string orderId, OrderStatusEnum orderTradingStatus, DateTime changeDt)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_INFO WHERE ORDERS_INFO_ID='" + orderId.Replace("'", "").Replace(",", "','") + "'");
            ds.Tables[0].TableName = this.TableName;

            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return "Error";
            }

            ds.Tables[0].Rows[0]["ORDER_STATUS"] = (int)orderTradingStatus;
            if (orderTradingStatus == OrderStatusEnum.PaiedAll)
            {
                ds.Tables[0].Rows[0]["ORDER_PAIED_TIME"] = changeDt;
            }

            this.Update(ds);
            return "OK";
        }

        /// <summary>
        /// 是否需要交 保证金 True需要  False 不需要
        /// </summary>
        /// <param name="order_solder_id">卖家id</param>
        /// <returns>string[]</returns>
        /// Author:蒲崇彬
        /// Creation date:2015-6-3
        public string[] WhetherBond(string order_solder_id)
        {

            //有违规行为 未缴纳保证金
            using (CBizViolationRecord vRecord = new CBizViolationRecord())
            {
                bool isVrecord = vRecord.IsViolationRecord(order_solder_id);
                if (isVrecord)
                {
                    return new string[] { "true", "有违规行为,未缴纳保证金" };
                }
            }

            using (CBizDjackSpecieInfo dsInfo = new CBizDjackSpecieInfo())
            {
                DataSet ds = dsInfo.SelectById(order_solder_id);
                if (ds == null)
                {
                    return new string[] { "true", "该地接客信息未找到" };
                }
                //已满3次 交易成功订单（或 已接业务3 个订单中） 需要缴纳保证金
                DataTable dt = ds.Tables[0];
                int tNumber = 0;
                int.TryParse(dt.Rows[0]["DJACK_TRADING_NUMBER"].ToString(), out tNumber);

                using (CBizCustomerBaseInfo baseinfo = new CBizCustomerBaseInfo())
                {
                    DataSet dsBase = baseinfo.GetUserAccountInfo(order_solder_id);
                    if (dsBase == null || dsBase.Tables[0].Rows.Count < 1)
                    {
                        return new string[] { "true", "该地接客信息未找到" };
                    }
                    //保证金数量
                    decimal bMoney = 0;
                    decimal.TryParse(dsBase.Tables[0].Rows[0]["CUSTOMER_SECDEP_ACCOUNT"].ToString(), out bMoney);

                    if (tNumber > 2 && bMoney < 1000)
                    {
                        return new string[] { "true", "想要接更多业务?需缴纳保证金" };
                    }
                }

            }
            return new string[] { "false", "没有任何违规记录" };
        }

        /// <summary>
        /// 地接客 订单状态处理修改   不能用于订单删除
        /// 1.确认订单 已判断是否有保证金 或已交易3笔业务
        /// 2.游客成功付款算一单，需要在付款成功后 添加地接客成功次数
        /// djkSpecieinfo   UpdateDjackStatus函数
        /// </summary>
        /// <param name="dijid">地接客编号</param>
        /// <param name="orderId">订单编号</param>
        /// <param name="orderStatus">订单状态</param>
        /// <returns>string[]</returns>
        /// Author:蒲崇彬
        /// Creation date:2015-6-3
        public string[] UpdateDjkOrderStatus(string dijid, string orderId, OrderStatusEnum orderStatus)
        {
            if (orderStatus == OrderStatusEnum.DeleteOrder)
            {
                return new string[] { "false", "删除失败" };
            }
            if (string.IsNullOrEmpty(dijid))
            {
                return new string[] { "false", "地接客编号不存在" };
            }
            if (string.IsNullOrEmpty(orderId))
            {
                return new string[] { "false", "信息不能为空" };
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderId", ParameterDirection.Input, EDbType.String, 36, orderId));
            parmCollection.Add(new CDbParm("UserId", ParameterDirection.Input, EDbType.String, 36, dijid));

            DataSet dsOrderInfo = this.DataObj.QueryBySQL(@"SELECT ORDER_CODE,ORDERS_INFO_ID,ORDER_SOLDER_ID,
    ORDER_STATUS,ORDER_IS_DJACK_DEL,ORDER_DJACKDEL_TIME,ORDER_DJACK_CHECK,ORDER_START_TIME
    FROM DJK_ORDERS_INFO
    WHERE ORDER_IS_DJACK_DEL=0 AND ORDERS_INFO_ID=@OrderId AND ORDER_SOLDER_ID=@UserId", parmCollection);

            if (dsOrderInfo == null || dsOrderInfo.Tables[0].Rows.Count <= 0)
            {
                return new string[] { "false", "该地接客不存在此订单" };
            }

            //商家确认 判断是否可以交易
            if (orderStatus == OrderStatusEnum.SolderChecked)
            {
                string[] solsers = WhetherBond(dijid);
                if (Convert.ToBoolean(solsers[0]))
                {
                    return new string[] { "false", solsers[1] };
                }
            }

            DataRow dr = dsOrderInfo.Tables[0].Rows[0];

            OrderStatusEnum serverStatus = (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString());
            //商家确认
            if (orderStatus == OrderStatusEnum.SolderChecked &&
                serverStatus != OrderStatusEnum.WaitingCheck)
            {
                return new string[] { "false", "当前订单状态不是等待确认" };
            }
            //确认退款
            else if (orderStatus == OrderStatusEnum.SurePayBack &&
                serverStatus != OrderStatusEnum.ApplyPayBack)
            {
                return new string[] { "false", "当前订单不是申请退款，不能确认退款" };
            }
            //拒绝退款
            else if (orderStatus == OrderStatusEnum.Refusal &&
                serverStatus != OrderStatusEnum.ApplyPayBack)
            {
                return new string[] { "false", "当前订单不是申请退款，不能拒绝退款" };
            }

            if (orderStatus == OrderStatusEnum.DeleteOrder)
            {
                if (serverStatus == OrderStatusEnum.Finished ||
                    serverStatus == OrderStatusEnum.CancelOrder ||
                    serverStatus == OrderStatusEnum.CloseStream)
                {
                    dr["ORDER_IS_DJACK_DEL"] = 1;
                    dr["ORDER_DJACKDEL_TIME"] = this.dtCurrDateTime;
                    dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
                }
            }
            else
            {
                dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
            }

            if (orderStatus == OrderStatusEnum.SolderChecked)
            {
                dr["ORDER_DJACK_CHECK"] = 1;


                if (this.dtCurrDateTime >= Convert.ToDateTime(dr["ORDER_START_TIME"].ToString()))
                {
                    return new string[] { "false", "当前状态已过期，不能确认订单" };
                }


                new CBizMessageSystem().AddMessage("[订单确认]你有一笔订单已确认。", string.Format("订单号为:{0}一笔订单 已确认，祝你旅途愉快&nbsp;&nbsp;<a class='nav-on' target='_blank' href='/ws_OrderInfo.htm?orderId={1}'>查看详情》</a>",
                       dr["ORDER_CODE"].ToString(),
                       dr["ORDERS_INFO_ID"].ToString()),
                       dr["ORDER_SOLDER_ID"].ToString());
            }
            dsOrderInfo.Tables[0].TableName = this.TableName;
            this.Update(dsOrderInfo);
            return new string[] { "true", "修改成功" };
        }

        /// <summary>
        /// 游客订单 状态修改
        /// </summary>
        /// <param name="buyerid">游客编号</param>
        /// <param name="orderId">订单编号</param>
        /// <param name="orderStatus">修改状态值</param>
        /// <returns>string[]</returns>
        /// Author:蒲崇彬
        /// Creation date:2015-6-3
        public string[] UpdateBuyerOrderStatus(string buyerid, string orderId, OrderStatusEnum orderStatus)
        {
            if (orderStatus == OrderStatusEnum.DeleteOrder)
            {
                return new string[] { "false", "删除失败" };
            }
            if (string.IsNullOrEmpty(buyerid))
            {
                return new string[] { "false", "游客编号不存在" };
            }
            if (string.IsNullOrEmpty(orderId))
            {
                return new string[] { "false", "信息不能为空" };
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderId", ParameterDirection.Input, EDbType.String, 36, orderId));
            parmCollection.Add(new CDbParm("UserId", ParameterDirection.Input, EDbType.String, 36, buyerid));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_BUYER_ID,ORDER_STATUS,
    ORDER_IS_CUSTOMER_DEL,ORDER_CUSDEL_TIME
    FROM DJK_ORDERS_INFO
    WHERE ORDER_IS_CUSTOMER_DEL=0 AND ORDERS_INFO_ID=@OrderId AND ORDER_BUYER_ID=@UserId", parmCollection);

            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return new string[] { "false", "该游客不存在此订单" };
            }

            DataRow dr = ds.Tables[0].Rows[0];

            OrderStatusEnum serverStatus = (OrderStatusEnum)Convert.ToInt32(dr["ORDER_STATUS"].ToString());
            //完成服务
            if (orderStatus == OrderStatusEnum.Finished &&
                serverStatus != OrderStatusEnum.PaiedAll)
            {
                return new string[] { "false", "当前订单状态未支付，不能完成服务" };
            }
            //申请退款
            else if (orderStatus == OrderStatusEnum.ApplyPayBack &&
                serverStatus != OrderStatusEnum.PaiedAll)
            {
                return new string[] { "false", "当前订单状态未支付，不能申请退款" };
            }
            //取消订单
            else if (orderStatus == OrderStatusEnum.CancelOrder &&
                serverStatus != OrderStatusEnum.WaitingCheck)
            {
                return new string[] { "false", "当前订单状态是等待确认，不能取消" };
            }
            //取消退款
            else if (orderStatus == OrderStatusEnum.RefundCanceled &&
                serverStatus != OrderStatusEnum.ApplyPayBack)
            {
                return new string[] { "false", "当前订单状态不是申请退款中，不能取消退款" };
            }

            //删除订单
            if (orderStatus == OrderStatusEnum.DeleteOrder)
            {
                if (serverStatus == OrderStatusEnum.Finished ||
                serverStatus == OrderStatusEnum.CancelOrder ||
                serverStatus == OrderStatusEnum.CloseStream)
                {
                    dr["ORDER_IS_CUSTOMER_DEL"] = 1;
                    dr["ORDER_CUSDEL_TIME"] = this.dtCurrDateTime;
                }
            }
            else
            {
                dr["ORDER_STATUS"] = Convert.ToInt32(orderStatus);
            }

            ds.Tables[0].TableName = this.TableName;
            this.Update(ds);
            return new string[] { "true", "修改成功" };
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <param name="orderid">订单id</param>
        /// <param name="isDjk">是否是地接客</param>
        /// <returns></returns>
        /// Author:蒲崇彬
        /// Creation date:2015-7-23 9:52
        public string DeleteOrder(string userid, string orderid, bool isDjk)
        {

            if (string.IsNullOrEmpty(userid))
            {
                return "该用户不存在";
            }
            if (string.IsNullOrEmpty(orderid))
            {
                return "该订单不存在";
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("OrderId", ParameterDirection.Input, EDbType.String, 36, orderid));
            parmCollection.Add(new CDbParm("UserId", ParameterDirection.Input, EDbType.String, 36, userid));
            string isDiJieKe = isDjk ? " AND ORDER_IS_DJACK_DEL=0 AND ORDER_SOLDER_ID=@UserId" : " AND ORDER_IS_CUSTOMER_DEL=0 AND ORDER_BUYER_ID=@UserId";
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT ORDERS_INFO_ID,ORDER_BUYER_ID,ORDER_STATUS,ORDER_IS_DJACK_DEL,
    ORDER_IS_CUSTOMER_DEL,ORDER_CUSDEL_TIME,ORDER_DJACKDEL_TIME,ORDER_START_TIME
    FROM DJK_ORDERS_INFO
    WHERE ORDERS_INFO_ID=@OrderId " + isDiJieKe, parmCollection);

            if (ds == null || ds.Tables[0].Rows.Count < 1)
            {
                return "该订单不存在.";
            }

            DataTable dt = ds.Tables[0];
            //取消订单，完成订单，过期订单，退款后，时间到了未付款,流程关闭   可以删除
            OrderStatusEnum orderStatus = (OrderStatusEnum)Convert.ToInt16(dt.Rows[0]["ORDER_STATUS"].ToString());
            DateTime starTime = Convert.ToDateTime(dt.Rows[0]["ORDER_START_TIME"].ToString());

            //时间到了未到 未付款 不能删除 
            if (orderStatus == OrderStatusEnum.SolderChecked && this.dtCurrDateTime < starTime)
            {
                return "该订单状态是不允许删除.";
            }
            //等待确认 时间未到不能删除
            else if (orderStatus == OrderStatusEnum.WaitingCheck && this.dtCurrDateTime < starTime)
            {
                return "该订单状态是不允许删除.";
            }
            // 申请退款 拒绝退款 不能删除
            else if (orderStatus == OrderStatusEnum.ApplyPayBack ||
                orderStatus == OrderStatusEnum.Refusal)
            {
                return "该订单状态是不允许删除.";
            }
            //已付款的 不能删除
            else if (orderStatus == OrderStatusEnum.PaiedAll)
            {
                return "该订单状态是不允许删除.";
            }

            #region
            ////已完成 未评论的不能删除
            //else if (orderStatus == OrderStatusEnum.Finished)
            //{
            //    //获取 评论状态
            //    using (CBizDJkOrdersDetail detail = new CBizDJkOrdersDetail())
            //    {
            //        DataSet dsDetail=detail.GetDetailByOrderInfoID(dt.Rows[0]["ORDERS_INFO_ID"].ToString());
            //        if (dsDetail!=null&&dsDetail.Tables[0].Rows.Count>0)
            //        {
            //           DataTable dtDetail= dsDetail.Tables[0];
            //           foreach (DataRow item in dtDetail.Rows)
            //           {
            //               if (Convert.ToInt16(item["IS_COMMENT"].ToString()) < 1)
            //               {
            //                   return "该订单未评论 不能删除";
            //               }
            //           }
            //        }
            //    }
            //}
            #endregion


            if (isDjk)
            {
                //地接客删除
                dt.Rows[0]["ORDER_IS_DJACK_DEL"] = 1;
                dt.Rows[0]["ORDER_DJACKDEL_TIME"] = this.dtCurrDateTime;
            }
            else
            {
                //游客删除
                dt.Rows[0]["ORDER_IS_CUSTOMER_DEL"] = 1;
                dt.Rows[0]["ORDER_CUSDEL_TIME"] = this.dtCurrDateTime;
            }

            ds.Tables[0].TableName = this.TableName;
            this.Update(ds);
            return "OK";
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="buyerid">买家ID 买家和卖家 可以一个为空</param>
        /// <param name="solderid">卖家ID</param>
        /// <param name="orderstatus">订单状态 0 为所有数据</param>
        /// <param name="pageIndex">第几页</param>
        ///<param name="pageSize">每页显示数量 默认10</param>
        /// <returns>DataSet</returns>
        /// Author:蒲崇彬
        /// Creation date:2015-6-8 10:00
        public DataSet GetOrderList(string buyerid, string solderid, OrderStatusEnum orderstatus, int pageIndex, int pageSize = 10)
        {
            if (string.IsNullOrEmpty(buyerid) && string.IsNullOrEmpty(solderid))
            {
                return null;
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("pageindex", ParameterDirection.Input, EDbType.Integer, 10, pageIndex));
            parmCollection.Add(new CDbParm("pagesize", ParameterDirection.Input, EDbType.Integer, 10, pageSize));
            parmCollection.Add(new CDbParm("buyerid", ParameterDirection.Input, EDbType.String, 36, buyerid));
            parmCollection.Add(new CDbParm("solderid", ParameterDirection.Input, EDbType.String, 36, solderid));
            parmCollection.Add(new CDbParm("orderstatus", ParameterDirection.Input, EDbType.Integer, 36, Convert.ToInt32(orderstatus)));

            return this.DataObj.QueryBySP("DJK_SELECT_ORDERS_LIST_VIEW", parmCollection);
        }

        /// <summary>
        /// 根据卖加 ID 和订单ID，查找订单信息
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="solderid">卖家 或者 买家ID </param>
        /// <param name="isDjk">是否为地接客 默认是</param>
        /// <returns>DataSet</returns>
        /// Author:蒲崇彬
        /// Creation date:2015-6-10 14:20
        public DataSet GetOrderInfoByUserAndOrderId(string orderId, string solderid, bool isDjk = true)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("orderId", ParameterDirection.Input, EDbType.String, 36, orderId));
            parmCollection.Add(new CDbParm("solderid", ParameterDirection.Input, EDbType.String, 36, solderid));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_INFO WHERE ORDERS_INFO_ID=@orderId " + (isDjk ? " AND ORDER_SOLDER_ID=@solderid " : " AND ORDER_BUYER_ID=@solderid "), parmCollection);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                ds.Tables[0].TableName = this.TableName;
            }

            return ds;
        }

        /// <summary>
        /// 添加订单信息
        /// </summary>
        /// <param name="vehiclesInfo">车辆信息(格式要求：车辆编号之间以'|'间隔，例如：Vehicle1ID|Vehicle2ID|Vehicle3ID.....)</param>
        /// <param name="startTime">开始服务时间</param>
        /// <param name="stopTime">结束服务时间</param>
        /// <param name="orderExpanation">备注内容</param>
        /// <returns></returns>
        /// Author:蒲崇彬
        /// Creation date:2015-6-12 15:11
        public string[] AddOrderInfoN(string vehiclesInfo, string startTime, string stopTime, string orderExpanation)
        {
            string userid = msBsc.SvRef.UserInfo.Operator;
            if (string.IsNullOrEmpty(userid))
            {
                return new string[] { "false", "登录过期，请重新登录在操作" };
            }

            if (string.IsNullOrEmpty(vehiclesInfo))
            {
                return new string[] { "false", "请选择至少一辆车进行预订" };
            }
            if (string.IsNullOrEmpty(startTime)
                || string.IsNullOrEmpty(stopTime))
            {
                return new string[] { "false", "服务开始日期和结束日期不能为空" };
            }

            DateTime startDate, stopDate;

            if (!DateTime.TryParse(startTime, out startDate)
                || !DateTime.TryParse(stopTime, out stopDate))
            {
                return new string[] { "false", "服务开始日期或结束日期有误，请调整" };
            }

            if (startDate < this.dtCurrDateTime)
            {
                return new string[] { "false", "服务开始日期必须大于当前日期" };
            }
            if (stopDate < startDate)
            {
                return new string[] { "false", "服务结束日期必须大于开始日期" };
            }

            //获取车辆信息
            DataSet productDs = new msBsc.AppLogic.DataAlc.CBizVehicleInfo().GetVehicleInfo(vehiclesInfo);
            if (productDs == null || productDs.Tables[0].Rows.Count < 1)
            {
                return new string[] { "false", "订购车辆信息失败，请至少选择一辆车进行预订！" };
            }
            //获取卖家id 地接客
            string solderid = productDs.Tables[0].Rows[0]["PERSON_ID"].ToString();
            if (string.IsNullOrEmpty(solderid))
            {
                return new string[] { "false", "该产品不存在" };
            }
            //获取是否绑定支付

            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                DateTime tempStopDate = (stopDate.Hour == 0 && stopDate.Minute == 0 && stopDate.Second == 0) ? stopDate : stopDate.AddDays(1);

                TimeSpan tsp = tempStopDate.Date.Subtract(startDate.Date);
                int serviceDays = tsp.Days;
                //计算 总价格 优惠价格
                decimal totalPrice = 0;
                decimal discountAMT = 0;
                foreach (DataRow item in productDs.Tables[0].Rows)
                {
                    totalPrice += Convert.ToDecimal(item["PRODUCT_PRICE"].ToString()) * serviceDays;
                }
                //订单ID
                string orderId = this.DataObj.NewID();
                //添加订单
                DataSet ds = new CDmDjkOrdersInfo();
                DataRow dr = ds.Tables[0].NewRow();

                dr["ORDERS_INFO_ID"] = orderId;
                dr["ORDER_TIME"] = this.dtCurrDateTime;
                dr["ORDER_CODE"] = "dlz" + this.dtCurrDateTime.ToString("yyyyMMddHHmmss") + msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("ORDER_CODE", "", 4);
                dr["ORDER_CONTENT"] = orderExpanation;
                dr["ORDER_STATUS"] = 1;
                dr["ORDER_BY_IP"] = msBsc.Cls.CommValiCollection.GetIp();
                dr["ORDER_START_TIME"] = startDate;
                dr["ORDER_STOP_TIME"] = stopDate;
                dr["ORDER_DJACK_CHECK"] = 0;
                dr["ORDER_TOTAL_BALANCE"] = totalPrice;
                dr["DISCOUNT_AMT"] = discountAMT;
                dr["PAYABLE_AMT"] = (totalPrice - discountAMT) * 0.2m;
                dr["ORDER_IS_CUSTOMER_DEL"] = 0;
                dr["ORDER_IS_DJACK_DEL"] = 0;
                dr["ORDER_HAS_REFUND"] = 0;
                dr["ORDER_BUYER_ID"] = userid;
                dr["ORDER_SOLDER_ID"] = solderid;
                dr["ORDER_REFUND_FINISH"] = 0;
                dr["DEPOSIT_RATIO"] = 0.2;
                ds.Tables[0].Rows.Add(dr);
                this.Update(ds);
                //添加订单 明细
                DataSet detailDs = new msBsc.AppLogic.DataAlc.CBizDJkOrdersDetail().AddOrderDetailN(orderId, productDs, serviceDays, 1);
                if (detailDs == null || detailDs.Tables[0].Rows.Count < 1)
                {
                    return new string[] { "false", "产品明细信息添加错误" };
                }
                //发送 消息
                new CBizMessageSystem().AddMessage("[订单确认]你有一笔订单等待确认。", string.Format("订单号为:{0}一笔订单 等待确认，即时和游客沟通会提高订单的成功概率哦&nbsp;&nbsp;<a class='nav-on' target='_blank' href='/ws_OrderInfo.htm?orderId={1}'>查看详情》</a>",
                      dr["ORDER_CODE"].ToString(),
                      dr["ORDERS_INFO_ID"].ToString()),
                      solderid);

                ts.Complete();
                return new string[] { "true", orderId };
            }
        }

        /// <summary>
        /// 获取各项查询 卖家 订单的数量
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        /// Author:蒲崇彬
        /// Creation date:2015-7-6 10:33
        public DataTable GetDjkAllSelectCount(string userid)
        {
            if (string.IsNullOrEmpty(userid))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();

            parmCollection.Add(new CDbParm("userid", ParameterDirection.Input, EDbType.String, 36, userid));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT 
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_DJACK_DEL=0 
AND ORDER_SOLDER_ID=@userid) sumcount,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_DJACK_DEL=0 
AND ORDER_SOLDER_ID=@userid AND ORDER_STATUS=1) daiquerren,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_DJACK_DEL=0 
AND ORDER_SOLDER_ID=@userid AND ORDER_STATUS=2) daifukuan,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_DJACK_DEL=0 
AND ORDER_SOLDER_ID=@userid AND ORDER_STATUS=3) yifukuan,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_DJACK_DEL=0 
AND ORDER_SOLDER_ID=@userid AND ORDER_STATUS=6) tuikuan,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_DJACK_DEL=0 
AND ORDER_SOLDER_ID=@userid AND ORDER_STATUS=4) wanchen", parmCollection);

            return ds != null ? ds.Tables[0] : ds.Tables[0];
        }

        /// <summary>
        /// 获取各项查询 买家 订单的数量
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        /// Author:蒲崇彬
        /// Creation date:2015-7-6 10:37
        public DataTable GetBuyerAllSelectCount(string userid)
        {
            if (string.IsNullOrEmpty(userid))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();

            parmCollection.Add(new CDbParm("userid", ParameterDirection.Input, EDbType.String, 36, userid));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT 
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_CUSTOMER_DEL=0 
AND ORDER_BUYER_ID=@userid) sumcount,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_CUSTOMER_DEL=0 
AND ORDER_BUYER_ID=@userid AND ORDER_STATUS=1) daiquerren,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_CUSTOMER_DEL=0 
AND ORDER_BUYER_ID=@userid AND ORDER_STATUS=2) daifukuan,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_CUSTOMER_DEL=0 
AND ORDER_BUYER_ID=@userid AND ORDER_STATUS=3) yifukuan,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_CUSTOMER_DEL=0 
AND ORDER_BUYER_ID=@userid AND ORDER_STATUS=6) tuikuan,
(SELECT COUNT(1) FROM DJK_ORDERS_INFO 
where ORDER_IS_CUSTOMER_DEL=0 
AND ORDER_BUYER_ID=@userid AND ORDER_STATUS=4) wanchen", parmCollection);

            return ds != null ? ds.Tables[0] : ds.Tables[0];
        }

        /// <summary>
        /// 订单结算
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool CloseAccount(string orderId)
        {
            DataSet ds = this.SelectById(orderId);

            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }

            ds.Tables[0].Rows[0]["IS_PAIEDFOR_DJK"] = 1;
            ds.Tables[0].Rows[0]["PAIEDFOR_DJK_DT"] = this.dtCurrDateTime;

            this.Update(ds);
            return true;
        }

        /// <summary>
        /// 获取准备进行结算的订单
        /// </summary>
        /// <returns>查询结果</returns>
        public DataSet GetReadyToCloseOrder()
        {
            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_ORDERS_FOR_CLOSE", null);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 后台获取订单信息
        /// </summary>
        /// <param name="orderCode"></param>
        /// <param name="orderDesc"></param>
        /// <param name="orderStatus"></param>
        /// <param name="buyerNick"></param>
        /// <param name="orderTimeStart">下单时间下限</param>
        /// <param name="orderTimeStop">下单时间上限</param>
        /// <returns></returns>
        public DataSet GetOrdersInfoForShpView(string orderCode, string orderDesc, int orderStatus, string buyerNick, string orderTimeStart, string orderTimeStop)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();

            parmCollection.Add(new CDbParm("ordercode", ParameterDirection.Input, EDbType.String, 36, orderCode.Replace(",", "','").Replace("'", "")));
            parmCollection.Add(new CDbParm("orderdesc", ParameterDirection.Input, EDbType.String, 255, orderDesc.Replace(",", "','").Replace("'", "")));
            parmCollection.Add(new CDbParm("orderstatus", ParameterDirection.Input, EDbType.Integer, 10, orderStatus));
            parmCollection.Add(new CDbParm("buyernike", ParameterDirection.Input, EDbType.String, 255, buyerNick.Replace(",", "','").Replace("'", "")));
            parmCollection.Add(new CDbParm("ordertimestart", ParameterDirection.Input, EDbType.String, 25, orderTimeStart.Replace(",", "','").Replace("'", "")));
            parmCollection.Add(new CDbParm("ordertimestop", ParameterDirection.Input, EDbType.String, 25, orderTimeStop.Replace(",", "','").Replace("'", "")));

            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_ORDERS_FOR_SHP_VIEW", parmCollection);
            ds.Tables[0].TableName = this.TableName;

            return ds;
        }

    }


    /// <summary>
    /// 订单状态枚举
    /// </summary>
    public enum OrderStatusEnum
    {
        /// <summary>
        /// 全部订单
        /// </summary>
        AllOrders = 0,
        /// <summary>
        /// 等待确认
        /// </summary>
        WaitingCheck = 1,
        /// <summary>
        /// 商家确认
        /// </summary>
        SolderChecked = 2,
        /// <summary>
        /// 已支付
        /// </summary>
        PaiedAll = 3,
        /// <summary>
        /// 已完成
        /// </summary>
        Finished = 4,
        /// <summary>
        /// 流程已关闭
        /// </summary>
        CloseStream = 5,
        /// <summary>
        /// 申请退款
        /// </summary>
        ApplyPayBack = 6,
        /// <summary>
        /// 确认退款 
        /// </summary>
        SurePayBack = 7,
        /// <summary>
        /// 取消订单
        /// </summary>
        CancelOrder = 8,
        /// <summary>
        /// 删除订单
        /// </summary>
        DeleteOrder = 9,
        /// <summary>
        /// 已取消退款
        /// </summary>
        RefundCanceled = 10,
        /// <summary>
        /// 拒绝退款
        /// </summary>
        Refusal = 11,
        /// <summary>
        /// 拒绝订单
        /// </summary>
        RefuseOrder = 12,
        /// <summary>
        /// 退款已完成
        /// </summary>
        FinishRefund = 13
    }
}
